package com.j1ay.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.j1ay.forum.dao.mapper.TypeMapper;
import com.j1ay.forum.model.pojo.po.Type;
import com.j1ay.forum.service.TypeService;
import com.j1ay.forum.model.pojo.vo.ErrorCode;
import com.j1ay.forum.model.pojo.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * @Author J1ay
 * @Date 2021/12/14 23:28
 * @Description
 */

@Service
public class TypeServiceImpl implements TypeService {
    @Autowired(required = false)
    private TypeMapper typeMapper;

    @Override
    public Type findTypeByTypeId(Long typeId) {
        System.out.println("==============>");
        System.out.println(this.typeMapper.selectById(typeId));
       return this.typeMapper.selectById(typeId);
    }

    @Override
    public Result getHots(int limit) {
        /**
         * 根据所属该分类的文章篇数来判定热门分类
         */
        List<Long> typeIds = this.typeMapper.findHotsTypeId(limit);
        if (CollectionUtils.isEmpty(typeIds)) {
            return Result.success(Collections.emptyList());
        }
        List<Type> typeList = this.typeMapper.findTypeByTypeId(typeIds);
        return Result.success(typeList);
    }

    @Override
    public Result getAllTypeList() {
        List<Type> typeList = this.typeMapper.selectList(new LambdaQueryWrapper<>());

        return Result.success(typeList);
    }


    @Override
    public Result delete(Long id) {
        if (null == id) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        int res = this.typeMapper.deleteById(id);
        if (0 == res) {
            return Result.fail(ErrorCode.SESSION_FAILED.getCode(), ErrorCode.SESSION_FAILED.getMsg());
        }
        return Result.success(null);
    }

    @Override
    public Result add(Type type) {
        if (StringUtils.isBlank(type.getTypeName())) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        int res = this.typeMapper.insert(type);
        if (0 == res) {
            return Result.fail(ErrorCode.SESSION_FAILED.getCode(), ErrorCode.SESSION_FAILED.getMsg());
        }
        return Result.success(null);
    }

    @Override
    public Result update(Type type) {
        if (null == type.getId()) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        int res = this.typeMapper.updateById(type);
        if (0 == res) {
            return Result.fail(ErrorCode.SESSION_FAILED.getCode(), ErrorCode.SESSION_FAILED.getMsg());
        }
        return Result.success(null);
    }
}
